﻿using DotNetty.Buffers;
using DotNetty.Transport.Channels;
using YanShu.Utils;
using System;
using YanShu.Entity;

namespace YanShu.Handler
{
    class RealServerChannelHandler : SimpleChannelInboundHandler<IByteBuffer>
    {
        protected override void ChannelRead0(IChannelHandlerContext ctx, IByteBuffer msg)
        {
            IChannel realServerChannel = ctx.Channel;
            IChannel channel = realServerChannel.GetAttribute(Constants.NEXT_CHANNEL).Get();
            if (channel == null)
            {
                // 代理客户端连接断开
                ctx.Channel.CloseAsync();
            }
            else
            {
                byte[] bytes = new byte[msg.ReadableBytes];
                msg.ReadBytes(bytes);
                String userId = ClientChannelMannager.GetRealServerChannelUserId(realServerChannel);
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.SetType(ProxyMessage.P_TYPE_TRANSFER);
                proxyMessage.SetUri(userId);
                proxyMessage.SetData(bytes);
                channel.WriteAndFlushAsync(proxyMessage);
            }
        }

        public override void ChannelActive(IChannelHandlerContext context)
        {
            MainWindow.SetText("激活本地连接");
            base.ChannelActive(context);
        }

        public override void ChannelInactive(IChannelHandlerContext context)
        {
            IChannel realServerChannel = context.Channel;
            String userId = ClientChannelMannager.GetRealServerChannelUserId(realServerChannel);
            ClientChannelMannager.RemoveRealServerChannel(userId);
            IChannel channel = realServerChannel.GetAttribute(Constants.NEXT_CHANNEL).Get();
            if (channel != null)
            {
                ProxyMessage proxyMessage = new ProxyMessage();
                proxyMessage.SetType(ProxyMessage.TYPE_DISCONNECT);
                proxyMessage.SetUri(userId);
                channel.WriteAndFlushAsync(proxyMessage);
            }
            base.ChannelInactive(context);

        }

        public override void ChannelWritabilityChanged(IChannelHandlerContext context)
        {
            IChannel realServerChannel = context.Channel;
            IChannel proxyChannel = realServerChannel.GetAttribute(Constants.NEXT_CHANNEL).Get();
            if (proxyChannel != null)
            {
                proxyChannel.Configuration.SetOption(ChannelOption.AutoRead, realServerChannel.IsWritable);
            }

            base.ChannelWritabilityChanged(context);
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            MainWindow.SetText(exception.Message);
            base.ExceptionCaught(context, exception);
        }

    }
}
